//
//  YFChatsVC.m
//  project
//
//  Created by Winny Zhang on 2019/3/22.
//  Copyright © 2019 健健. All rights reserved.
//

#import "YFChatsVC.h"
#import "HJChatRoomVC.h"
#import "YFEmptyView.h"
#import "YFChatListCell.h"
#import "HJRCIMManager.h"
#import "HJFriendsCell.h"
#import "HJSystemMsgVC.h"
#import "HJSimpleMessage.h" /// 自定义消息
#import "HJFriendsListModel.h"
static NSString * const ChatListCellIdentifier = @"ChatListCellIdentifier";
static NSString * const SystemCellIdentifier = @"SystemCellIdentifier";

@interface YFChatsVC ()<RCIMClientReceiveMessageDelegate>
@property (nonatomic,strong) NSMutableArray <RCConversationModel*>* conversationDataSources;
@property (nonatomic,strong) NSString * unreadCount;
//@property (nonatomic, strong) NSMutableArray *friendList;
@end

@implementation YFChatsVC

//-(NSMutableArray *)willReloadTableData:(NSMutableArray *)dataSource {
//    RCConversationModel * conversationModel = [[RCConversationModel alloc]init];
//    conversationModel.conversationType = RC_CONVERSATION_MODEL_TYPE_CUSTOMIZATION;
//    conversationModel.conversationTitle = @"系统消息";
//    conversationModel.isTop = YES;
//    conversationModel.unreadMessageCount = 2;
//    [dataSource insertObject:conversationModel atIndex:0];
//    return dataSource;
//}

//#pragma mark - Cell 点击方法
//- (void)onSelectedTableRow:(RCConversationModelType)conversationModelType conversationModel:(RCConversationModel *)model atIndexPath:(NSIndexPath *)indexPath {
//    // 清空消息未读条数
//    [[RCIMClient sharedRCIMClient] clearMessagesUnreadStatus:model.conversationType targetId: model.targetId];
//    // 进入聊天室
//    HJChatRoomVC * chatRoomVC = [[UIStoryboard storyboardWithName:@"Chat" bundle:nil] instantiateViewControllerWithIdentifier:chatRoom];
//    chatRoomVC.natitle = model.conversationTitle;
////    LKLog(@"聊天室title：%@", model.yy_modelToJSONString);
//
//    chatRoomVC.conversationModel = model;
//    [self.navigationController pushViewController:chatRoomVC animated:YES];
//}


- (void)viewDidLoad {
    [super viewDidLoad];
    [self requestSystemUnReadMsgCount];
    //清空目标会话未读消息
    [mNotificationCenter addObserver:self selector:@selector(clearMessagesUnreadNotification:) name:NotificationRCReceive object:nil];
    // 清除系统消息未读数
    [mNotificationCenter addObserver:self selector:@selector(clearSystemUnReadNotification) name:NotificationClearSystem object:nil];
    // 用户修改了个人信息 通知
    [mNotificationCenter addObserver:self selector:@selector(refreshRCUserInfo:) name:NotificationRCUserInfo object:nil];
    // 设置消息接收监听
    [[RCIMClient sharedRCIMClient] setReceiveMessageDelegate:self object:nil];
    
//    [[RCIM sharedRCIM] registerMessageType:[HJSimpleMessage class]];
    [[RCIMClient sharedRCIMClient]registerMessageType:[HJSimpleMessage class]];
    
    [mNotificationCenter addObserver:self selector:@selector(loadLocalLastMessage:) name:@"localLasteMessage" object:nil];
    
}
-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self loadMsgCount];
    [self setBadgeOnItemIndex];
}
- (void)onReceived:(RCMessage *)message left:(int)nLeft object:(id)object {
    LKLog(@"收到消息%@",message.content);
    [self loadDataRefresh];
}
- (void)loadLocalLastMessage:(NSNotification *)notification {
    [self loadDataRefresh];
}


/**
 系统消息未读数
 */
-(void)requestSystemUnReadMsgCount {
    NSString * url = [Api stringByAppendingString:GetUnreadMsgCountApi];
    [HJHttpTool get:url params:nil success:^(HJResponeds *result) {
//        LKLog(@"%@",result.data);
        self.unreadCount = result.data;
        [self loadDataRefresh];
    } failure:^(id result) {
    }];
}

/**
 清除系统消息未读数
 */
-(void)clearSystemUnReadNotification {
    self.unreadCount = @"0";
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.tableView reloadData];
    });
}

/**
 下拉刷新
 */
-(void)loadNetworkData {
    [self loadDataRefresh];
}
/**
 加载会话消息列表数据
 */
- (void)loadDataRefresh {//RCConversationModel
    NSArray * dataSource = [NSArray arrayWithArray:[[RCIMClient sharedRCIMClient] getConversationList:@[@(ConversationType_PRIVATE)]]];
    self.conversationDataSources = [NSMutableArray arrayWithCapacity:dataSource.count];
    @weakify(self)
    for (RCConversation * conversation in dataSource) {
        [[RCIM sharedRCIM].userInfoDataSource getUserInfoWithUserId:conversation.targetId completion:^(RCUserInfo *userInfo) {
            @strongify(self)
            RCConversationModel * model = [RCConversationModel new];
            model.extend = userInfo;
            model.receivedTime = conversation.receivedTime;
            model.targetId = conversation.targetId;
            model.objectName = conversation.objectName;
            model.lastestMessage = conversation.lastestMessage;
            model.lastestMessageId = conversation.lastestMessageId;
            model.sentTime = conversation.sentTime;
            model.conversationType = ConversationType_PRIVATE;
            model.jsonDict = conversation.jsonDict;
            model.lastestMessageDirection = conversation.lastestMessageDirection;
            model.senderUserId = conversation.senderUserId;
            model.unreadMessageCount = conversation.unreadMessageCount;
            model.conversationTitle = conversation.conversationTitle;
            [self.conversationDataSources addObject:model];
            
            [self.tableView reloadData];
        }];
    }
    [self.tableView endRefresh];
}

-(void)configTableView {
    self.needHeaderRefresh = YES;
    self.tableViewStyle = UITableViewStylePlain;
    [super configTableView];
    self.tableView.rowHeight = 60;
    self.tableView.separatorInset = UIEdgeInsetsMake(0, 50, 0, 0);
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    self.tableView.separatorColor = [UIColor colorWithHex:0xf2f2f2];
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 20, 0);
    self.tableView.emptyView = [YFEmptyView view];
    [[HJRCIMManager manager] configRC];
}

#pragma mark --清空聊天消息未读数据
-(void)clearMessagesUnreadNotification:(NSNotification *)noti {
    NSString * targetID = noti.userInfo[@"clearMsgTarget"];
    // 清空未读消息数
    [[RCIMClient sharedRCIMClient] clearMessagesUnreadStatus:ConversationType_PRIVATE targetId:targetID];
}
#pragma mark --修改用户信息通知
-(void)refreshRCUserInfo:(NSNotification *)notification {
    RCUserInfo * userinfo = [[RCUserInfo alloc]initWithUserId:[HJUserManager getUserModel].userId name:[HJUserManager getUserModel].nickName portrait:[HJUserManager getUserModel].avatar];
    [[RCIM sharedRCIM] refreshUserInfoCache:userinfo withUserId:[HJUserManager getUserModel].userId];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section==0) {
        return [self systemMsg].count;
    }
    return self.conversationDataSources.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    YFChatListCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (!cell) {
        cell = [[YFChatListCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:ChatListCellIdentifier];
    }
    if (indexPath.section==0) {
        HJFriendsCell * systemCell = [tableView cellForRowAtIndexPath:indexPath];
        if (!systemCell) {
            systemCell = [[HJFriendsCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SystemCellIdentifier];
        }
        systemCell.promptLabel.hidden = self.unreadCount.integerValue == 0;
        systemCell.promptLabel.text = [NSString stringWithFormat:@"%zd",self.unreadCount.integerValue];;
        NSDictionary * dic = [self systemMsg][indexPath.row];
        systemCell.name.text = dic[@"title"];
        systemCell.headImage.image = setImage(dic[@"image"]);
        
        return systemCell;
        
    }else if (indexPath.section==1) {
        RCConversationModel *model = self.conversationDataSources[indexPath.row];
        cell.model  = model;
        LKLog(@"target = %@", model.targetId);
        return cell;
    }
    return nil;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [UIView new];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 5;
}

-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section==0) return NO;
    return YES;
}

#pragma mark - 设置cell的删除事件
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.row == 0){
        return UITableViewCellEditingStyleNone;
    }else{
        return UITableViewCellEditingStyleDelete;
    }
}
-(NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewRowAction * deleteAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        RCConversationModel *model = self.conversationDataSources[indexPath.row];
        [self.conversationDataSources removeObject:model];
        [tableView reloadData];
    }];
    deleteAction.backgroundColor = [UIColor redColor];
    return @[deleteAction];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    switch (indexPath.section) {
        case 0:// 系统消息
        {
            self.unreadCount = @"0";
            HJSystemMsgVC * systemVC =[[HJSystemMsgVC alloc]init];
            [self.navigationController pushViewController:systemVC animated:YES];
            [tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
        }
            break;
        default:// 聊天室
        {
            YFChatListCell *cell = (YFChatListCell *)[tableView cellForRowAtIndexPath:indexPath];
            HJChatRoomVC * chatRoomVC = [[UIStoryboard storyboardWithName:@"Chat" bundle:nil]instantiateViewControllerWithIdentifier:chatRoom];
            RCConversationModel * conversationModel = self.conversationDataSources[indexPath.row];
            RCUserInfo * userInfo = (RCUserInfo *)conversationModel.extend;
            conversationModel.conversationTitle = userInfo.name;
            conversationModel.unreadMessageCount = 0;
            cell.model = conversationModel;
            // 清空消息未读条数
            [[RCIMClient sharedRCIMClient] clearMessagesUnreadStatus:conversationModel.conversationType targetId: conversationModel.targetId];
            [tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:indexPath.row inSection:1]] withRowAnimation:UITableViewRowAnimationNone];
            chatRoomVC.conversationModel = conversationModel;
            [self.navigationController pushViewController:chatRoomVC animated:YES];
        }
            break;
    }
}

#pragma mark -- 消息未读数
-(void)loadMsgCount {

}
#pragma mark -- 设置、清除tabbar角标数
-(void)setBadgeOnItemIndex {
    
}

-(void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    self.tableView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGTH-NAVIGATION_BAR_HEIGHT-Height_TabBar);
}

-(NSArray<NSDictionary *> *)systemMsg {//@{@"image":@"newfriends",@"title":@"新朋友"}
    NSArray * systemMsg = @[@{@"image":@"system_chat",@"title":@"系统消息"}];
    return systemMsg;
}

#pragma mark - 获取好友信息


@end

